<?php
/**
 * Created by PhpStorm.
 * User: heitao
 * Date: 2018/5/9
 * Time: 13:39
 */

namespace manniu\model;

use think\Model;

abstract class Base extends Model
{
    /**
     * 生成随机数
     * @param int $length 随机数长度
     * @return string
     */
    public function builderRand($length = 8){
        return substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, $length);
    }

    /**
     * 格式化缓存键名的风格
     * @param $key
     * @param $params
     * @return mixed
     */
    protected function formatCacheKey($key, $params, $type = 'redis'){
        if(empty($key) || empty($key)){
            throw new \think\Exception('缓存键名/格式化风格不能为空！');
        }
        if(!is_array($params) || count($params)<1){
            throw new \think\Exception('缓存键名的组合参数必须是数组且不能为空数组！');
        }
        switch(strtolower($type)){
            case 'redis':
                $separator = ':';
                break;
            case 'memcached':
                $separator = '|';
                break;
            case 'file':
                $separator = '_';
                break;
            default:
                $separator = '_';
        }
        $format_key = '';
        foreach ($params as $k => $item){
            $format_key .= str_replace('{'.$k.'}', $separator.$item.$separator, $key);
        }
        $format_key = trim($format_key, $separator);
        return strtolower($format_key);
    }
}